"use client";

import useCategories from "@/app/hooks/categories.hook";
import { useNotifications } from "@/app/hooks/notification.hook";
import itemsService from "@/app/services/items.service";
import FileUploader from "@/components/photo-uploader/page";
import CustomSelect from "@/components/select/select";
import Item, { ItemCategory } from "@/shared/item";
import { useRouter } from "next/navigation";
import { useState } from "react";

export default function AddItemPage() {
  const router = useRouter();
  const { showError, showSuccess } = useNotifications();
  const [item, setItem] = useState<Item & { category: ItemCategory }>();
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const { categories } = useCategories();

  const handleChange = (e: React.FormEvent<HTMLInputElement>) => {
    setItem((prev) => {
      return { ...prev, [e.target.name]: e.target.value };
    });
  };

  const handleSubmit = async () => {
    try {
      await itemsService.createItem(item!, selectedFile ?? undefined);
      router.push("/manage");
      showSuccess("Позиция успешно добавлена");
    } catch {
      showError("Ошибка при добавлении позиции");
    }
  };
  return (
    <section className="manage" style={{ flex: 2 }}>
      <h1 className="heading">
        Добавление <span>позиции</span>
      </h1>
      <div className="row">
        <div className="info">
          <div className="row">
            <div className="item f1">
              <span>Фото:</span>
              <FileUploader
                setSrc={(src) => {
                  setSelectedFile(src);
                }}
                src={""}
              />
            </div>
            <div className="col f1">
              <div className="item">
                <span>Наименование:</span>
                <div className="inputBox">
                  <span className="fa  fa-asterisk"></span>
                  <input
                    type="text"
                    value={item?.name}
                    placeholder="Наименование"
                    name="name"
                    onChange={handleChange}
                  />
                </div>
              </div>
              <div className="item">
                <span>Категория:</span>
                <CustomSelect
                  placeholder={"Категория.."}
                  options={categories.map((cat) => ({
                    label: cat.name,
                    value: cat.id,
                  }))}
                  onChange={(val) => {
                    setItem((prev) => ({
                      ...prev,
                      categoryId: val,
                    }));
                  }}
                />
              </div>
            </div>
          </div>
          <div className="row">
            <div className="item">
              <span>Описание:</span>
              <div className="inputBox">
                <span className="fas fa-font"></span>
                <input
                  value={item?.description}
                  type="text"
                  placeholder="Описание"
                  onChange={handleChange}
                  name="description"
                />
              </div>
            </div>
          </div>
          <div className="row">
            <div className="item">
              <span>Стоимость:</span>
              <div className="inputBox">
                <span className="fa fa-rub"></span>
                <input
                  type="text"
                  value={item?.price}
                  placeholder="Стоимость"
                  onChange={(e) => {
                    if (Number.parseFloat(e.target.value)) handleChange(e);
                  }}
                  name="price"
                />
              </div>
            </div>
          </div>
          <input
            style={{
              width: "50%",
              margin: "10px auto",
            }}
            type="submit"
            value="Добавить"
            onClick={handleSubmit}
            className="btn"
          />
        </div>
      </div>
    </section>
  );
}
